package com.tanhua.dubbo.server.service;

import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 将发布动态的信息 异步写入好友的时间线表中
     * @param userId        // 发布动态的用户id
     * @param publishId     // 这个是动态id
     */
    @Async //异步执行，原理：底层开一个线程去执行该方法
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId) {

        try {
            // 1. 根据用户id到MongoDB中查询到 对应的好友信息
            Query query = new Query(Criteria.where("userId").is(userId));
            List<Users> users = mongoTemplate.find(query, Users.class);

            if (users.isEmpty()){
                return CompletableFuture.completedFuture("ok");
            }

            // 2. 依次将发布的动态 写入好友的时间表中
            for (Users user : users) {
                TimeLine timeLine = new TimeLine();
                timeLine.setPublishId(publishId);
                timeLine.setUserId(userId);
                timeLine.setId(ObjectId.get());
                timeLine.setDate(System.currentTimeMillis());

                // 将信息写入
                mongoTemplate.save(timeLine,"quanzi_time_line_" + user.getFriendId());
            }
        } catch (Exception e) {
            log.error("写入好友时间线表失败~ userId = " + userId + ", publishId = " + publishId, e);
            //TODO 事务回滚问题
            return CompletableFuture.completedFuture("error");
        }

        return CompletableFuture.completedFuture("ok");
    }
}
